/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.admin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.yami.shop.common.bean.Qiniu;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.ImgUploadUtil;
import com.yami.shop.service.AttachFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.StorageClass;
/**
 * 文件上传 controller
 * @author lgh
 *
 */
@RestController
@RequestMapping("/admin/file")
public class FileController {
	@Value("${malladmin.uploadpath}")
	private String uploadPath;
	@Value("${malladmin.useoss}")
	private boolean useOSS;
	@Value("${aliyun.oss.endpoint}")
	private String endpoint;
	@Value("${aliyun.oss.stsEndpoint}")
	private String stsEndpoint;
	@Value("${aliyun.oss.accessKeyId}")
	private String accessKeyId;
	@Value("${aliyun.oss.accessKeySecret}")
	private String accessKeySecret;
	@Value("${aliyun.oss.bucketName}")
	private String bucketName;
	@Autowired
	private AttachFileService attachFileService;
	@Autowired
	private Qiniu qiniu;
	@Autowired
	private ImgUploadUtil imgUploadUtil;





	public String sendToOSS(String fileName){
		// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
		//String endpoint = endpoint;
		// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
		//String accessKeyId = accessKeyId;
		// String accessKeySecret = accessKeyS;
		// 填写Bucket名称，例如examplebucket。
		//String bucketName = "examplebucket";
		// 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
		String url="";
		String tmp=fileName.substring(fileName.lastIndexOf("/")+1);
		//DateUtil.format(new Date(), "yyyy/MM/dd");
		String objectName = DateUtil.format(new Date(), "yyyy/MM/dd/")+tmp;
		// 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
		// 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
		String filePath= fileName;

		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		try {
			// 创建PutObjectRequest对象。
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
			// 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
			metadata.setObjectAcl(CannedAccessControlList.PublicRead);
			putObjectRequest.setMetadata(metadata);

			// 上传文件。
			ossClient.putObject(putObjectRequest);
			url="http://" + bucketName + "." + endpoint + "/" + objectName;
		} catch (OSSException oe) {
			System.out.println("Caught an OSSException, which means your request made it to OSS, "
					+ "but was rejected with an error response for some reason.");
			System.out.println("Error Message:" + oe.getErrorMessage());
			System.out.println("Error Code:" + oe.getErrorCode());
			System.out.println("Request ID:" + oe.getRequestId());
			System.out.println("Host ID:" + oe.getHostId());
		} catch (ClientException ce) {
			System.out.println("Caught an ClientException, which means the client encountered "
					+ "a serious internal problem while trying to communicate with OSS, "
					+ "such as not being able to access the network.");
			System.out.println("Error Message:" + ce.getMessage());
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
		return  url;

	}

	@PostMapping("/upload/element")
	public ServerResponseEntity<String> uploadElementFile(@RequestParam("file") MultipartFile file) throws IOException{
		if(file.isEmpty()){
			return ServerResponseEntity.success();
		}
		String extName = FileUtil.extName(file.getOriginalFilename());
		String fileName =DateUtil.format(new Date(), "yyyy/MM/")+ IdUtil.simpleUUID() + "." + extName;

		String fullFileName = uploadPath+fileName;


		File newfile = new File(fullFileName);
		if (!newfile.exists()) {
			boolean result = newfile.mkdirs();
			if (!result) {
				throw new YamiShopBindException("创建目录：" + fullFileName + "失败");
			}
		}
		try {
			file.transferTo(newfile);
		} catch (IOException e) {
			throw new YamiShopBindException("上传失败");
		}
		if(!useOSS){
			return  ServerResponseEntity.success(fileName);
		}
		String ret=sendToOSS(fileName);
		return ServerResponseEntity.success(ret);
	}
	


	@PostMapping("/upload/tinymceEditor")
	public ServerResponseEntity<String> uploadTinymceEditorImages(@RequestParam("editorFile") MultipartFile editorFile) throws IOException{
		return uploadElementFile(editorFile);
	}
	

	
}
